package com.meng.mmlive.ui.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.PtrHandler;
import com.meng.baselibrary.activity.BaseActivity;
import com.meng.mmlive.App;
import com.meng.mmlive.R;
import com.meng.mmlive.mvp.presenter.SessionPressenter;
import com.meng.mmlive.mvp.view.SessionView;
import com.meng.mmlive.ui.adapter.SessionRecyclerViewAdapter;
import com.meng.mmlive.ui.widget.PtrClassicHeader;
import com.meng.mmlive.utils.KeyboardUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.ReadReceiptMessage;
import io.rong.message.TextMessage;

/**
 * Created by LG on 2017/5/15.
 * 会话界面（单聊、群聊）
 * 目前只实现单聊
 */

public class SessionActivity extends BaseActivity implements SessionView, PtrHandler {
    public final static int SESSION_TYPE_PRIVATE = 1;
    public final static int SESSION_TYPE_GROUP = 2;
    @Inject
    SessionPressenter sessionPressenter;
    @Bind(R.id.toolbar_ti)
    Toolbar toolbarTi;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.send_btn)
    Button sendBtn;
    @Bind(R.id.input_et)
    EditText inputEt;
    @Bind(R.id.refleshLayout)
    PtrClassicFrameLayout refleshLayout;
    private SessionRecyclerViewAdapter sessionRecyclerViewAdapter;
    private List<Message> mDatas = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_session);
    }

    @Override
    protected void initView() {
        initPaddingTob();
        ButterKnife.bind(this);
        //当软键盘弹出时，让RecyclerView自动滚动到显示最后一个item
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(layoutManager);
        PtrClassicHeader header = (PtrClassicHeader) LayoutInflater.from(this).inflate(R.layout.v_ptrclass_header,null);
        refleshLayout.setHeaderView(header);
        refleshLayout.addPtrUIHandler(header);
        refleshLayout.setPtrHandler(this);
        setSupportActionBar(toolbarTi);//使用Toolbar对象替换ActionBar
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//设置返回箭头显示
        //设置标题
        getSupportActionBar().setTitle(getIntent().getStringExtra("sessionId"));
        //监听toolbar返回键
        toolbarTi.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //监听软键盘弹起
        View rootView = getWindow().getDecorView().getRootView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(KeyboardUtil.isKeyboardShown(rootView)){
                    if(!keyboardShow){
                        recyclerView.scrollToPosition(mDatas.size()-1);
                        keyboardShow = true;
                    }
                }else{
                    keyboardShow = false;
                }
            }
        });
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(keyboardShow){
                    KeyboardUtil.hideKeyboard(SessionActivity.this,inputEt);
                }
                return false;
            }
        });
        //设置消息回执监听器
        RongIMClient.setReadReceiptListener(new RongIMClient.ReadReceiptListener() {
            @Override
            public void onReadReceiptReceived(Message message) {
                if(mSessionId.equals(message.getTargetId())){
                    ReadReceiptMessage content = (ReadReceiptMessage) message.getContent();
                    long ntfTime = content.getLastMessageSendTime();    //获取发送时间戳
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sessionRecyclerViewAdapter.updateMsgReadedStatus(ntfTime);
                        }
                    });

                }
            }

            @Override
            public void onMessageReceiptRequest(Conversation.ConversationType conversationType, String s, String s1) {

            }

            @Override
            public void onMessageReceiptResponse(Conversation.ConversationType conversationType, String s, String s1, HashMap<String, Long> hashMap) {

            }
        });
    }
    private boolean keyboardShow;
    String mSessionId;
    @Override
    protected void initData() {
        App.instance.getSessionComponent().inject(this);
        sessionPressenter.attachView(this);
        mSessionId = getIntent().getStringExtra("sessionId");
        sessionPressenter.clearMessagesUnreadStatus(mSessionId);//清除未读消息状态
        sessionPressenter.loadData(mSessionId); //加载历史消息
    }
    @Override
    public void showMessages(List<Message> messages) {
        for (int i = 0; i < messages.size(); i++) {
            mDatas.add(0, messages.get(i));
        }
        if (sessionRecyclerViewAdapter == null) {
            sessionRecyclerViewAdapter = new SessionRecyclerViewAdapter(this, mDatas);
            recyclerView.setAdapter(sessionRecyclerViewAdapter);
            //发送已读回执
            RongIMClient.getInstance().sendReadReceiptMessage(Conversation.ConversationType.PRIVATE,mSessionId,messages.get(0).getSentTime());
        } else {
            sessionRecyclerViewAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void addMessage(Message message) {
        mDatas.add(message);
        sessionRecyclerViewAdapter.notifyDataSetChanged();
        //如果显示了最后一个item
        if(layoutManager.findLastVisibleItemPosition() == layoutManager.getItemCount()-2
                || message.getMessageDirection() == Message.MessageDirection.SEND){
            recyclerView.scrollToPosition(mDatas.size()-1);
        }
    }

    @Override
    public void pullLoadComplete() {
        refleshLayout.refreshComplete();
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onMessageEvent(Message message) {
        addMessage(message);
        sessionPressenter.clearMessagesUnreadStatus(mSessionId);//清除未读消息状态
        //发送已读回执
        RongIMClient.getInstance().sendReadReceiptMessage(Conversation.ConversationType.PRIVATE,mSessionId,message.getSentTime());
    }

    ;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sessionPressenter.detachView();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R.id.send_btn)
    public void onClick() {
        RongIMClient.getInstance().sendMessage(
                Conversation.ConversationType.PRIVATE, mSessionId, TextMessage.obtain(inputEt.getText().toString()),
                null, null, new IRongCallback.ISendMediaMessageCallback() {
                    @Override
                    public void onProgress(Message message, int i) {
                    }

                    @Override
                    public void onCanceled(Message message) {
                    }

                    @Override
                    public void onAttached(Message message) {
                        addMessage(message);
                    }

                    @Override
                    public void onSuccess(Message message) {
                        sessionRecyclerViewAdapter.updateMessageStatus(message.getMessageId(),message.getSentStatus());
                    }

                    @Override
                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                        sessionRecyclerViewAdapter.updateMessageStatus(message.getMessageId(),message.getSentStatus());
                    }
                });
        inputEt.getText().clear();
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame,content,header)
                &&sessionPressenter.hasMoreMessage();
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        sessionPressenter.loadData(mSessionId);
    }
}
